﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetfractionHub.Network.Protocol;
using NetfractionHub.Network.Protocol.BASE.Factory;

namespace NetfractionHub.LocalMachine.BotCommands.Announcer
{
    [CommandHandler("addrelease")]
    public class AddRelease : CommandHandler
    {
        public override bool HandleCommandMessage(NetfractionHub.RemoteMachine.Node source, CommandMessage message)
        {
            string magnet = string.Empty;
            string catName = string.Empty;
            int catId = 0;
            int userId = 0;

            if (message.ArgumentsCount == 2)
            {
                if (message.StringArguments.Count == 2)
                {
                    if (message.StringArguments.ContainsKey("magnet"))
                    {
                        magnet = message.StringArguments["magnet"];
                    }
                    else
                    {
                        // missing magnet
                        return false;
                    }

                    if (message.StringArguments.ContainsKey("categoryName"))
                    {
                        catName = message.StringArguments["categoryName"];
                        catId = GetCategoryIdFromName(catName);
                        if (catId == 0)
                        {
                            return false;
                        }
                    }
                    else if (message.StringArguments.ContainsKey("categoryId") && int.TryParse(message.StringArguments["categoryId"], out catId))
                    {
                        catName = GetCategoryNameFromId(catId);
                        if (string.IsNullOrEmpty(catName))
                        {
                            return false;
                        }
                    }
                    else
                    {
                        // missing category
                        return false;
                    }
                }
                else if (message.UnnamedArguments.Count == 2)
                {
                    if (int.TryParse(message.UnnamedArguments[0], out catId))
                    {
                        catName = GetCategoryNameFromId(catId);
                        if (string.IsNullOrEmpty(catName))
                        {
                            return false;
                        }
                    }
                    else
                    {
                        catName = message.UnnamedArguments[0];
                        catId = GetCategoryIdFromName(catName);
                        if (catId == 0)
                        {
                            return false;
                        }
                    }

                    magnet = message.UnnamedArguments[1];
                }

                // get userId for username, or add it.
                userId = GetUserIdFromUsername(source.Identity.Nickname);
                if (userId == 0)
                {
                    userId = InsertUser(source.Identity.Nickname);
                    if (userId == 0)
                    {
                        return false;
                    }
                }

                int retVal = AnnouncerBot.DataStore.ExecuteNonQuery(String.Format(System.Globalization.CultureInfo.InvariantCulture, "INSERT INTO Entries (AddedBy, CategoryId, Magnet) VALUES ({0}, {1}, '{2}')", userId, catId, magnet));
                if (retVal == 1)
                {
                    this.ParentBot.SendBroadcastMessageFromBot(String.Format(System.Globalization.CultureInfo.InvariantCulture, "The entry '{0}' has been added to the Announcer database, under the category '{1}'.", magnet, catName));
                }
            }
            else if (message.ArgumentsCount == 1)
            {
                if (message.StringArguments.Count == 1 && message.StringArguments.ContainsKey("magnet"))
                {
                    magnet = message.StringArguments["magnet"];
                }
                else if (message.UnnamedArguments.Count == 1)
                {
                    magnet = message.UnnamedArguments[0];
                }
                int retVal = AnnouncerBot.DataStore.ExecuteNonQuery(String.Format(System.Globalization.CultureInfo.InvariantCulture, "INSERT INTO Entries (AddedBy, Magnet) VALUES ({0}, {1}, '{2}')", userId, magnet));
                if (retVal == 1)
                {
                    this.ParentBot.SendBroadcastMessageFromBot(String.Format(System.Globalization.CultureInfo.InvariantCulture, "The entry '{0}' has been added to the Announcer database.", magnet));
                }
            }
            else
            {
                return false;
            }

            return true;
        }

        private int GetUserIdFromUsername(string name)
        {
            object tempVal = AnnouncerBot.DataStore.ExecuteScalar(String.Format(System.Globalization.CultureInfo.InvariantCulture, "SELECT UserId FROM Users WHERE Username='{0}'", name));
            if (tempVal != null && tempVal is Int64)
            {

                return CastInt64ToInt((Int64)tempVal);
            }
            else
            {
                return 0;
            }
        }

        private int CastInt64ToInt(Int64 num)
        {
            if (num > int.MinValue && num < int.MaxValue)
            {
                return Convert.ToInt32(num);
            }
            else
            {
                return 0;
            }
        }

        private int InsertUser(string name)
        {
            int retVal = AnnouncerBot.DataStore.ExecuteNonQuery(String.Format(System.Globalization.CultureInfo.InvariantCulture, "INSERT INTO Users (Username) VALUES ('{0}')", name));
            if (retVal == 1)
            {
                return GetUserIdFromUsername(name);
            }
            return 0;
        }

        private int GetCategoryIdFromName(string name)
        {
            object tempVal = AnnouncerBot.DataStore.ExecuteScalar(String.Format(System.Globalization.CultureInfo.InvariantCulture, "SELECT CategoryId FROM Categories WHERE Name='{0}'", name));
            if (tempVal != null && tempVal is Int64)
            {
                return CastInt64ToInt((Int64)tempVal);
            }
            else
            {
                return 0;
            }
        }

        private string GetCategoryNameFromId(int id)
        {
            object tempVal = AnnouncerBot.DataStore.ExecuteScalar(String.Format(System.Globalization.CultureInfo.InvariantCulture, "SELECT Name FROM Categories WHERE CategoryId='{0}'", id));
            if (tempVal != null && tempVal is string)
            {
                return tempVal.ToString();
            }
            else
            {
                return string.Empty;
            }
        }
    }
}
